package com.ycb.controller;

import com.ycb.entity.User;
import com.ycb.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.util.Map;

/**
 * @author 黄泽群
 * @since 2023-12-11
 */
@RestController
@RequestMapping("/")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final ApplicationContext applicationContext;

    @GetMapping("/")
    public String test() throws Exception {
        System.err.println(111);
        Map<String, DataSource> map = applicationContext.getBeansOfType(DataSource.class);
        for (Map.Entry<String, DataSource> entry : map.entrySet()) {
            DataSource dataSource = entry.getValue();
            System.err.println(entry.getKey()+" - "+dataSource);
//                ConnectionBuilder connectionBuilder = ds.createConnectionBuilder();
//                Connection connection = connectionBuilder.build();
//                Statement statement = connection.createStatement();
//                boolean execute = statement.execute("select 1");
//                System.err.println(execute);
//            Connection connection = dataSource.getConnection();
//            Statement statement = connection.createStatement();
//            boolean execute = statement.execute("select 1");
//            System.err.println(execute);

        }
        System.err.println(222);
        return "";
    }

    @GetMapping("sub-amount")
    public User subAmount(@RequestParam(name = "userId",required = false,defaultValue = "1") Integer userId,
                          @RequestParam(name = "subAmt",required = false,defaultValue = "1") Integer subAmt){
        User user = userService.getById(userId);
        if (user.getAmt() < subAmt){
            throw new RuntimeException("用户余额不足");
        }
        user.setAmt(user.getAmt() - subAmt);
        userService.updateById(user);
        return user;
    }
}
